<?php
header("content-type:text/html;charset=utf8");
/**
 * 自定义文件异常类
 * @Author: blue
 * @Date:   2017-05-22 10:17:17
 * @Last Modified by:   blue
 * @Last Modified time: 2017-05-22 11:27:10
 */
class FileException extends Exception{
	public function getDetail(){
		switch ($this->code) {
			case 0:
				return '请输入文件名';
				break;
			case 1:
				return '文件不存在';
				break;
			case 2:
				return '文件打开模式有问题';
				break;
			case 3:
				return '文件不可读';
				break;
			case 4:
				return '文件写入失败';
				break;
			case 5:
				return '文件已关闭';
				break;
			default:
				return '非法操作';
				break;
		}
	}
}
/**
 * 文件读取类
 */
class FileRead{
	protected $_message;
	protected $_fp;
	public function __construct($filename,$mode='w'){
		$this->_message="文件名称:{$filename} 打开模式:{$mode}".PHP_EOL;
		if(empty($filename)) throw new FileException("$this->_message", 0);
		if(!is_file($filename)) throw new FileException($this->_message, 1);
		if(!in_array($mode,['w','w+','a','a+'])) throw new FileException($this->_message, 2);
		if(!is_writable($filename)) throw new FileException($this->_message, 3);
		echo "文件正常打开";
		$this->_fp=fopen($filename, $mode);		
	}
	//文件写入,异常抛出
	public function write($data){
		if(!fwrite($this->_fp, $data.PHP_EOL)) throw new Exception("文件写入失败", 4);
	}
	//关闭文件,异常抛出
	public function close(){
		if($this->_fp){
			if(!fclose($this->_fp)) throw new Exception("文件关闭失败", 5);
			$this->_fp=null;
		}
	}
	//析构函数
	public function __destruct(){
		$this->close();
	}
}
//代码实现
try {
	$f=new FileRead('test.php','w');
	$f->write('you a dog');
	$f->close();
	echo "数据写入成功";
} catch (FileException $e) {
	echo $e->getMessage()."|".$e->getDetail();
}
